package com.b2c.repository;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.xhs.XhsOrderEntity;
import com.b2c.entity.xhs.XhsRefundEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Repository
public class XhsRefundRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(rollbackFor = Exception.class)
    public ResultVo<Long> pullRefund(XhsRefundEntity refund)  {
        /**********查询订单信息**********/
        //erp系统发货状态（判断是否出库是否需要拦截）0未处理2已出库
        int erpSendStatus = 0;
        XhsOrderEntity order = null;
        try {
            order = jdbcTemplate.queryForObject("SELECT * FROM dc_xhs_order WHERE orderId=?", new BeanPropertyRowMapper<>(XhsOrderEntity.class), refund.getPackageId());
            erpSendStatus = order.getErpSendStatus();
        }catch (Exception e){}

        Long refundId = jdbcTemplate.queryForObject("SELECT IFNULL((select id from dc_xhs_refund where returnsId=? limit 1),0) id ", Long.class, refund.getReturnsId());
        if (refundId > 0) {
            //订单存在，更新订单状态
            jdbcTemplate.update("update dc_xhs_refund set returnType=?,reason=?,status=?," +
                            "subStatus=?,receiveAbnormalType=?,packageId=?," +
                            "exchangePackageId=?,returnExpressNo=?,returnExpressCompany=?," +
                            "returnAddress=?," +
                            "shipNeeded=?,refunded=?,refundStatus=?," +
                            "autoReceiveDeadline=?,updateTime=?,erpSendStatus=? where id=?",
                    refund.getReturnType(), refund.getReason(), refund.getStatus(),
                    refund.getSubStatus(),refund.getReceiveAbnormalType(),refund.getPackageId(),
                    refund.getExchangePackageId(),refund.getReturnExpressNo(),refund.getReturnExpressCompany(),refund.getReturnAddress(),
                    refund.getShipNeeded(), refund.getRefunded(),refund.getRefundStatus(),
                    refund.getAutoReceiveDeadline(),refund.getUpdateTime(),erpSendStatus, refundId);

            return new ResultVo<>(EnumResultVo.DataExist, "已存在，更新状态",refundId);
        }

        /*****1、添加order*****/
        StringBuilder orderInsertSQL = new StringBuilder();
        orderInsertSQL.append("INSERT INTO dc_xhs_refund");
        orderInsertSQL.append(" SET ");
        orderInsertSQL.append(" returnsId=?,");
        orderInsertSQL.append(" returnType=?,");
        orderInsertSQL.append(" reasonId=?,");
        orderInsertSQL.append(" shopId=?,");
        orderInsertSQL.append(" reason=?,");
        orderInsertSQL.append(" status=?,");
        orderInsertSQL.append(" subStatus=?,");
        orderInsertSQL.append(" receiveAbnormalType=?,");
        orderInsertSQL.append(" packageId=?,");
        orderInsertSQL.append(" exchangePackageId=?,");
        orderInsertSQL.append(" createdTime=?,");
        orderInsertSQL.append(" returnExpressNo=?,");
        orderInsertSQL.append(" returnExpressCompany=?,");
        orderInsertSQL.append(" returnAddress=?,");
        orderInsertSQL.append(" shipNeeded=?,");
        orderInsertSQL.append(" refunded=?,");
        orderInsertSQL.append(" refundStatus=?, ");
        orderInsertSQL.append(" autoReceiveDeadline=?,");
        orderInsertSQL.append(" updateTime=?,");
        orderInsertSQL.append(" erpSendStatus=?,");
        orderInsertSQL.append(" returnExpressCompanyCode=?");

        try {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            int finalErpSendStatus = erpSendStatus;
            jdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(orderInsertSQL.toString(), Statement.RETURN_GENERATED_KEYS);
                    ps.setString(1, refund.getReturnsId());
                    ps.setInt(2, refund.getReturnType());
                    ps.setInt(3, refund.getReasonId());
                    ps.setInt(4, refund.getShopId());
                    ps.setString(5, refund.getReason());
                    ps.setInt(6, refund.getStatus());
                    ps.setInt(7, refund.getSubStatus());
                    ps.setInt(8, refund.getReceiveAbnormalType());
                    ps.setString(9, refund.getPackageId());
                    ps.setString(10, refund.getExchangePackageId());
                    ps.setLong(11, refund.getCreatedTime());
                    ps.setString(12, refund.getReturnExpressNo());
                    ps.setString(13, refund.getReturnExpressCompany());
                    ps.setString(14, refund.getReturnAddress());
                    ps.setInt(15, refund.getShipNeeded());
                    ps.setInt(16, refund.getRefunded());
                    ps.setInt(17, refund.getRefundStatus());
                    ps.setInt(18, refund.getAutoReceiveDeadline().intValue());
                    ps.setLong(19, refund.getUpdateTime());
                    ps.setInt(20, finalErpSendStatus);
                    ps.setString(21, refund.getReturnExpressCompanyCode());

                    return ps;
                }
            }, keyHolder);

            Long orderIdNew = keyHolder.getKey().longValue();
            //更新订单售后状态
            jdbcTemplate.update("UPDATE dc_xhs_order SET afterSalesStatus=2 WHERE orderId=?",refund.getPackageId());


            return new ResultVo<>(EnumResultVo.SUCCESS, "成功",orderIdNew);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultVo<>(EnumResultVo.Fail, "异常：" + e.getMessage());
        }
    }

    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

    @Transactional
    public PagingResponse<XhsRefundEntity> getRefundList(Integer shopId, Integer pageIndex, Integer pageSize) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT SQL_CALC_FOUND_ROWS  A.* ");
        sb.append(" FROM dc_xhs_refund A ");
        sb.append(" WHERE A.shopId=? ");

        List<Object> params = new ArrayList<>();
        params.add(shopId);

        sb.append(" ORDER BY A.createdTime DESC LIMIT ?,?");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        List<XhsRefundEntity> lists = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(XhsRefundEntity.class), params.toArray(new Object[params.size()]));
        int totalSize = getTotalSize();
        return new PagingResponse<>(pageIndex, pageSize, totalSize, lists);
    }

    public XhsRefundEntity getRefundDetailById(Long id){
        try {
            return jdbcTemplate.queryForObject("SELECT * FROM dc_xhs_refund WHERE id=? ",new BeanPropertyRowMapper<>(XhsRefundEntity.class),id);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 处理仅退款
     * @param id
     */
    @Transactional
    public void agreeRefundOnly(Long id) {
        try {
            var refund = jdbcTemplate.queryForObject("SELECT * FROM dc_xhs_refund WHERE id=? ", new BeanPropertyRowMapper<>(XhsRefundEntity.class), id);

            jdbcTemplate.update("UPDATE dc_xhs_refund SET status=4,refundStatus=2,refunded=1,updateTime=? WHERE id=?", System.currentTimeMillis(), id);

            //更新订单
            jdbcTemplate.update("UPDATE dc_xhs_order SET orderStatus=9,afterSalesStatus=3 WHERE orderId=?",refund.getPackageId());
//            return new ResultVo<>(EnumResultVo.SUCCESS, "成功",orderIdNew);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return new ResultVo<>(EnumResultVo.Fail, "异常：" + e.getMessage());
        }
    }
}
